package com.bw.module_mine.login.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.state.Default
import com.bw.lib_common.base.state.Empty
import com.bw.lib_common.base.state.Failed
import com.bw.lib_common.base.state.Loading
import com.bw.lib_common.base.state.Success
import com.bw.lib_common.observeWithLifecycle
import com.bw.lib_storage.mmkv.AppMMKV
import com.bw.lib_storage.mmkv.AuthMMKV
import com.bw.module_mine.R
import com.bw.module_mine.databinding.FragmentLoginBinding
import com.bw.module_mine.login.viewmodel.UserViewModel
import com.bw.module_mine.utils.ToastUtils
import com.bw.module_mine.utils.ValidUtil
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class LoginFragment : BaseFragment<UserViewModel,FragmentLoginBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_login

    private val mViewModel:UserViewModel by activityViewModels()
    private lateinit var mNavController: NavController
    override fun initView() {
        super.initView()
        mViewModel.setShowingFragmentTag(LoginFragment::class.simpleName!!)
        mNavController = Navigation.findNavController(mBinding.root)
    }

    override fun initData() {
        mBinding.viewmodel = mViewModel
    }

    override fun initListener() {

        mBinding.btn.setOnClickListener{
            login()
        }
        mBinding.toRegister.setOnClickListener{
           mNavController.navigate(R.id.action_loginFragment_to_registerFragment)
        }


        mViewModel.LoginEvent.observeWithLifecycle(this){
             when(it){
                 is Success -> {
                     ToastUtils.showShort(context, "登录成功")
                     requireActivity().finish()


                 }
                 is Failed -> {
                     ToastUtils.showShort(context, it.message)
                 }

                 Default -> {

                 }
                 Empty -> {

                 }
                 Loading -> {
                     ToastUtils.showShort(context, "登录中")
                 }
             }
        }
    }


    fun login(){
        val password = mViewModel.password.value
        val phone = mViewModel.phone.value

        if (!ValidUtil.phoneNumberValid(phone)) {
            ToastUtils.showShort(context, "手机号码长度错误")
            return
        }

        if(password.length == 0){
            ToastUtils.showShort(context, "请先输入密码")
            return
        }

        mViewModel.login(password,phone)

    }


}